package org.linkerproject.setting;

import java.util.List;

import org.jdom.Element;
import org.linkerproject.html.HtmlLink;
import org.linkerproject.html.HtmlPage;

public class UrlManager {

	public UrlManager(String localPath) {

		// Get urls;
		urlSetting = new SettingFile(null, localPath + "/urls.html");
		if (urlSetting.getValue("urls.url") == null) {
			initUrls(urlSetting);
		}
		urls = urlSetting.getElement("urls");
	}

	public void initUrls(SettingFile file) {
		System.out.println("init urls");
		file.setValue("urls.url.title", "Hao123");
		file.setValue("urls.url.url", "http://www.hao123.com");
		file.save();
	}

	public String getUrlHtml() {
		HtmlPage html = new HtmlPage("urls");
		HtmlLink link;
		List<?> list = urls.getChildren("url");

		Object[] urlElements = list.toArray();

		for (Object o : urlElements) {
			Element e;
			if (o instanceof Element) {
				e = (Element) o;
			} else {
				continue;
			}

			String title = e.getChildText("title");
			String url = e.getChildText("url");

			link = new HtmlLink(title, url);
			html.addBodyContent(link);
		}

		HtmlLink addLink = new HtmlLink("Add Url", "addurl.mars");
		html.addBodyContent(addLink);

		System.out.println(html.output());
		return html.output();
	}

	public void addUrl(String title, String url) {
		Element e = new Element("url");
		Element urlElement = new Element(url);
		Element titleElement = new Element(title);
		e.addContent(urlElement);
		e.addContent(titleElement);

		urls = urlSetting.getElement("urls");
		urls.addContent(e);
		urlSetting.save();
	}

	public void removeUrl(String url) {

		Element[] urlElements = (Element[]) urls.getChildren().toArray();
		for (Element e : urlElements) {
			if (e.getChildText("url").startsWith(url)) {
				urls.removeContent(e);
			}
		}
		urlSetting.save();
	}

	private SettingFile urlSetting;

	private Element urls;

}
